import axios from 'axios';
import Cookies from 'js-cookie'
import QS from 'qs';
import {
	ElMessage
} from 'element-plus'
import { getToken } from './cookies.js'
// import { useI18n } from "vue-i18n";
// const locale = useI18n()

axios.defaults.baseURL = 'https://api.ava-loading1.com'
axios.interceptors.request.use( //响应拦截
	async config => {
		// console.log(locale,'语言')
		config.headers['Lang'] = Cookies.get('lang') || 'zh'
		if (getToken()) {
			config.headers['token'] = getToken('tokne')
		}
		return config;
	},
	error => {
		return Promise.error(error);
	})
// 响应拦截器
axios.interceptors.response.use(
	response => {
		if (response.data.code === 1) {
			return Promise.resolve(response); //进行中        
		} else {
			ElMessage({
				message: response.data.msg,
				type: 'error',
			})
			return Promise.reject(response); //失败       
		}
	},
	error => {
		ElMessage({
			message: error.data.msg || 'error',
			type: 'error',
		})
		return Promise.reject(error.response);
	}
);

const $get = (url, params) => {
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: params,
		})
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data)
			})
	});
}

const $post = (url, params) => {
	return new Promise((resolve, reject) => {
		axios.post(url, QS.stringify(params)) 
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data)
			})
	});
}

export default {
	install: (app) => {
		app.config.globalProperties['$get'] = $get;
		app.config.globalProperties['$post'] = $post;
		app.config.globalProperties['$axios'] = axios;
	}
}